#set( $symbol_pound = '#' )
#set( $symbol_dollar = '$' )
#set( $symbol_escape = '\' )
package ${package}.controller;

import ${package}.context.BooleanPropertyEditor;
import ${package}.context.DatePropertyEditor;
import ${package}.context.OpenIdUserInfo;
import ${package}.model.Member;
import java.security.Principal;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.springframework.mobile.device.Device;
import org.springframework.security.openid.OpenIDAuthenticationToken;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import springdao.DaoManager;
import springdao.RepositoryManager;
import springdao.support.DaoPropertyEditor;

/**
 *
 * @author Kent Yeh
 */
@Controller
public class DefaultController {

    private static Logger logger = LogManager.getLogger(DefaultController.class);
    @DaoManager
    private RepositoryManager<Member> memberManager;

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(Date.class, new DatePropertyEditor());
        binder.registerCustomEditor(Boolean.class, new BooleanPropertyEditor());
        binder.registerCustomEditor(Member.class, new DaoPropertyEditor(memberManager));
    }

    @RequestMapping("/")
    public String root(Device device, Model model) {
        if (device.isMobile()) {
            logger.debug("Connect devcie is mobile");
            model.addAttribute("device", "mobile");
            //return "mobileIndex";
        } else if (device.isTablet()) {
            logger.debug("Connect devcie is tablet");
            model.addAttribute("device", "tablet");
            //return "tabletIndex";
        } else {
            model.addAttribute("device", "normal");
            logger.debug("Connect device is normal device.");
        }
        return "index";
    }

    private String getPrincipalId(Principal principal) {
        Object p = principal instanceof OpenIDAuthenticationToken ? ((OpenIDAuthenticationToken) principal).getPrincipal() : principal;
        return p instanceof OpenIdUserInfo ? ((OpenIdUserInfo) p).getId() : principal.getName();
    }

    /**
     * Response all users' data as json.
     *
     * @return
     */
    @RequestMapping(value = "/admin/users", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String listuser() {
        List<Member> users = memberManager.findByCriteria("WHERE enabled=?1 ORDER BY name", "Y");
        if (users == null || users.isEmpty()) {
            return "{${symbol_escape}"total${symbol_escape}":0,${symbol_escape}"users${symbol_escape}":[]}";
        } else {
            StringBuilder sb = new StringBuilder("{${symbol_escape}"total${symbol_escape}":").append(users.size()).append(",${symbol_escape}"users${symbol_escape}":[");
            boolean isFirst = true;
            for (Member user : users) {
                if (!isFirst) {
                    sb.append(",");
                }
                sb.append("{${symbol_escape}"account${symbol_escape}":${symbol_escape}"").append(user.getId()).append("${symbol_escape}",${symbol_escape}"name${symbol_escape}":${symbol_escape}"").append(user.getName())
                        .append("${symbol_escape}",${symbol_escape}"birthday${symbol_escape}":${symbol_escape}"").append(String.format("%tF", user.getBirthDay())).append("${symbol_escape}"}");
                isFirst = false;
            }
            sb.append("]}");
            return sb.toString();
        }
    }

    /**
     * display current user's info.
     *
     * @param request
     * @param principal
     * @return
     */
    @RequestMapping("/user/myinfo")
    public String myinfo(HttpServletRequest request, Principal principal) {
        request.setAttribute("member", memberManager.findByPrimaryKey(getPrincipalId(principal)));
        return "index";
    }

    /**
     * Only adminstrator could display any user's info.
     *
     * @param account
     * @param request
     * @return
     */
    @RequestMapping("/admin/user/{account}")
    public String userinfo(@PathVariable Member account, HttpServletRequest request) {
        if (account != null) {
            request.setAttribute("member", account);
        }
        return "index";
    }
}
